import React, { useEffect, useState } from 'react';
import { Table, Form, Row, Col, Button, Input, Divider, Upload, Alert, message, Modal} from 'antd';
import { connect, useDispatch } from 'umi';
import PageTopFormContent from '@/components/PageTopFormContent';
import styles from './actionmanage.less';
import PaginationCommon from '@/components/PaginationCommon';
import ActionEdit from './components/ActionEdit';
import axios from 'axios';
const layout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 16 },
};

const { confirm } = Modal;

const ActionManage = (props) => {
  const {
    resourceActionManageModel,
    common,
    loading: { effects },
  } = props;
  const { appCodeOfSelect } = common;
  const { resourceList, resourceTotal } = resourceActionManageModel;
  const [formData, setFormData] = useState({});
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [selectedRows, setSelectedRows] = useState([]);
  const [fileUploading, setFileUploading] = useState(false);
  const [currentPageNum, setCurrentPageNum] = useState(1);
  const [currentPageSize, setCurrentPageSize] = useState(10);
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [editData, setEditData] = useState({});
  const [lookDisabled, setLookDisabled] = useState(false);
  const [drawerType, setDrawerType] = useState('add');
  const dispatch = useDispatch();
  const [form] = Form.useForm();

  const handleSearch = () => {
    const { validateFields } = form;
    validateFields().then((values) => {
      const param = { ...values };
      setFormData(param);
      setCurrentPageNum(1);
    });
  };

  const handleReset = () => {
    form.resetFields();
    setCurrentPageNum(1);
    setFormData({});
  };

  const handlePaginationChange = (page, pageSize) => {
    setCurrentPageNum(page);
    setCurrentPageSize(pageSize);
  };

  const selectResourceList = () => {
    const { resourceId, resourceName } = formData;
    const paramsData = {
      pageIndex: currentPageNum,
      pageSize: currentPageSize,
      resourceId,
      resourceName,
      appCode: appCodeOfSelect,
    };
    dispatch({
      type: 'resourceActionManageModel/selectResource',
      payload: paramsData,
    });
  };

  useEffect(() => {
    selectResourceList();
  }, [currentPageNum, currentPageSize, formData, appCodeOfSelect]);

  const rowSelection = {
    selectedRowKeys,
    onChange: (selectedRowKeysParam, selectedRowsParam) => {
      setSelectedRowKeys(selectedRowKeysParam);
      setSelectedRows(selectedRowsParam);
    },
  };

  const handleShowDrawer = (type, record) => {
    setDrawerVisible(true);
    setDrawerType(type);
    const data = {
      resourceCode: record.resourceCode,
      resourceName: record.resourceName,
      resourceId: record.id,
      appCode: appCodeOfSelect,
    };
    setEditData(data);
    if (type === 'look') {
      setLookDisabled(true);
    }
  };

  const handleCloseDrawer = (update = false) => {
    setDrawerVisible(false);
    setEditData({});
    setLookDisabled(false);
    if (update) {
      handleSearch();
    }
  };

  const resetSelection = () => {
    setSelectedRowKeys([]);
    setSelectedRows([]);
  };

  const handleExport = async () => {

    if (selectedRowKeys.length === 0) {
      message.warn("请选择需要导出的菜单！");
      return;
    }

    try {
      const response = await axios.post('/usercenter-admin-app/admin/sysResource/export', {
        appCode: appCodeOfSelect,
        resourceIds: [...selectedRowKeys]
      }, {
        responseType: 'blob' // 设置响应类型为blob
      });
      const nowDate = parseInt((new Date().getTime() / 1000).toString());
      // 创建一个新的a标签
      const link = document.createElement('a');
      link.href = URL.createObjectURL(new Blob([response.data]));
      link.download = nowDate + '_data.xml'; // 替换为要下载的文件名
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    } catch (error) {
      console.error('下载文件失败：', error);
    }
    resetSelection();
  };

  const batchDelete = () => {
    if (selectedRows.length > 0) {
      const param = {
        appCode: appCodeOfSelect,
        resourceIds: [...selectedRowKeys]
      }
      confirm({
        title: `确定要批量删除菜单？`,
        onOk() {
          handleDelete(param);
        },
      });
    } else {
      message.warn('请选择要删除的菜单');
    }
  };

  const handleDelete = (props) => {
    dispatch({
      type: 'resourceActionManageModel/removeResource',
      payload: props,
    }).then((res) => {
      const { code, message: errMsg } = res;
      if (code === 0) {
        message.success('删除成功');
        handleSearch();
      } else {
        message.error(errMsg);
      }
    });
  }

  const columns = [
    {
      title: '菜单 ID',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '菜单编码',
      dataIndex: 'resourceCode',
      key: 'resourceCode',
    },
    {
      title: '菜单名称',
      dataIndex: 'resourceName',
      key: 'resourceName',
    },
    {
      title: '创建人',
      dataIndex: 'creator',
      key: 'creator',
    },
    {
      title: '创建时间',
      dataIndex: 'gmtCreated',
      key: 'gmtCreated',
    },
    {
      title: '修改人',
      dataIndex: 'modifier',
      key: 'modifier',
    },
    {
      title: '修改时间',
      dataIndex: 'gmtModified',
      key: 'gmtModified',
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      fixed: 'right',
      render: (record) => (
        <div>
          <Divider type="vertical" />
          <Button type="link" onClick={() => handleShowDrawer('look', record)}>
            按钮详情
          </Button>
          <Divider type="vertical" />
          <Button type="link" onClick={() => handleShowDrawer('edit', record)}>
            按钮修改
          </Button>
        </div>
      ),
    },
  ];

  return (
    <div className={styles.root}>
      <PageTopFormContent
        title="按钮权限管理"
        content={
          <Form {...layout} form={form} name="advanced_search">
            <Row gutter={[32, 16]}>
              <Col className="gutter-row" span={6}>
                <Form.Item name="resourceId" label="菜单ID">
                  <Input placeholder="请输入菜单ID" />
                </Form.Item>
              </Col>
              <Col className="gutter-row" span={6}>
                <Form.Item name="resourceName" label="菜单名称">
                  <Input placeholder="请输入菜单名称" />
                </Form.Item>
              </Col>

              <Col span={12} style={{ textAlign: 'right' }}>
                <Form.Item wrapperCol={{ span: 24 }}>
                  <Button type="primary" onClick={handleSearch}>
                    查询
                  </Button>
                  <Button style={{ marginLeft: 16 }} onClick={handleReset}>
                    重置
                  </Button>
                </Form.Item>
              </Col>
            </Row>
          </Form>
        }
      />
      <div className={styles.tableWapper}>
        <div className={styles.listHead}>
          <div className={styles.listTitle}>菜单列表</div>
          <div className={styles.btnGroup}>
            {selectedRowKeys.length !== 0 && (
              <Alert
                type="info"
                message={
                  <>
                    已选中 <strong>{selectedRowKeys.length}</strong> 条数据
                    <Button
                      type="link"
                      size="small"
                      onClick={() => {
                        resetSelection();
                      }}
                    >
                      清空
                    </Button>
                  </>
                }
                style={{ display: 'inline-block', padding: '3px 6px' }}
              />
            )}
            <Button
              className={styles.marginLeft}
              onClick={batchDelete}
              type="danger"
              disabled={selectedRows.length === 0}
            >批量删除</Button>
            <Button onClick={handleExport}>菜单同步-导出</Button>
            <Upload
              showUploadList={false}
              name="file"
              action={`/usercenter-admin-app/admin/sysResource/import?appCode=${appCodeOfSelect}`}
              onChange={(e) => {
                const { status, response } = e.file;
                if (status === 'uploading') {
                  setFileUploading(true);
                } else if (status === 'done') {
                  // 如果上传返回有错误，则提示错误信息，重置 loading 状态
                  if (response && response.code !== 0) {
                    message.error(response?.message || '导入失败');
                  } else {
                    message.success(response?.data || '导入成功');
                    handleReset();
                  }
                  setFileUploading(false);
                }
              }}
            >
              <Button className={styles.marginLeft} loading={fileUploading}>
                菜单同步-导入
              </Button>
            </Upload>
          </div>
        </div>

        <div className={styles.listTable}>
          <Table
            rowKey="id"
            rowSelection={{
              ...rowSelection,
            }}
            columns={columns}
            dataSource={resourceList}
            pagination={false}
            scroll={{ x: 'max-content' }}
            loading={effects['resourceActionManageModel/selectResource']}
          />
          <PaginationCommon
            style={{ textAlign: 'right' }}
            total={resourceTotal}
            onChange={handlePaginationChange}
            current={currentPageNum}
            pageSize={currentPageSize}
          />
        </div>
      </div>
      {drawerVisible && (
        <ActionEdit
          drawerType={drawerType}
          lookDisabled={lookDisabled}
          editData={editData}
          handleCloseDrawer={handleCloseDrawer}
        />
      )}
    </div>
  );
};

export default connect((state) => state)(ActionManage);
